﻿
Option Explicit On
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MsgBox("ok")

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        'Me.Hide()
        Form2.ShowDialog()
    End Sub


    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        ExportToExcel()

    End Sub



    Sub ExportToExcel()

        ' 创建一个新的Excel工作簿
        Dim excelApp As Excel.Application
        excelApp = New Excel.Application()
        excelApp.Visible = True

        ' 添加数据到工作簿
        Dim workbook As Excel.Workbook
        Dim worksheet As Excel.Worksheet
        workbook = excelApp.Workbooks.Add()
        worksheet = workbook.Worksheets.Add()

        worksheet.Range("A1").Value = "Name"
        worksheet.Range("B1").Value = "Age"
        worksheet.Range("C1").Value = "City"

        worksheet.Range("A2").Value = "Alice"
        worksheet.Range("B2").Value = 25
        worksheet.Range("C2").Value = "New York"

        worksheet.Range("A3").Value = "Bob"
        worksheet.Range("B3").Value = 30
        worksheet.Range("C3").Value = "San Francisco"

        worksheet.Range("A4").Value = "Cathy"
        worksheet.Range("B4").Value = 35
        worksheet.Range("C4").Value = "Los Angeles"

        worksheet.Range("A5").Value = "David"
        worksheet.Range("B5").Value = 40
        worksheet.Range("C5").Value = "Chicago"

        ' 保存工作簿到Excel文件
        Dim filePath As String
        filePath = "C:\output.xlsx"
        workbook.SaveAs(filePath)

        ' 关闭工作簿和Excel应用程序
        worksheet.Close()
        workbook.Close()
        excelApp.Quit()

    End Sub



End Class
